package cn.mw.cmdb.service.handler.monitorData;

import cn.mw.cmdb.entity.ItemDropInfo;
import cn.mw.cmdb.enums.ChartTypeEnum;
import cn.mw.cmdb.param.ItemNameParam;
import cn.mw.cmdb.param.MwBaseMonitorDataResult;
import cn.mw.cmdb.param.MwItemHistoryResult;
import cn.mw.cmdb.param.QueryItemHistoryParam;
import cn.mw.cmdb.param.zabbixResult.MWItemHistoryDTO;
import cn.mw.cmdb.param.zabbixResult.MwMonitorHistoryParam;
import cn.mw.cmdb.processor.MonitorParamContext;
import cn.mw.cmdb.processor.MonitorProcessor;
import cn.mw.cmdb.service.MwMonitorProcessorConvert;
import cn.mw.cmdb.service.impl.CmdbServiceManage;
import cn.mw.main.api.common.ZabbixDubboService;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.enums.ChartTypeEnum.getChartEnumByName;
import static cn.mw.cmdb.service.handler.monitorData.MonitorHandlerUtils.*;

/**
 * 趋势数据查询
 */
public class MonitorTrendHandler implements HistoryHandlerProcessor<MwMonitorHistoryParam> {

    private CmdbServiceManage cmdbServiceManage;
    private ZabbixDubboService zabbixDubboService;
    private final String avgType = "value_avg";
    private final String minType = "value_min";
    private final String maxType = "value_max";

    public MonitorTrendHandler(CmdbServiceManage cmdbServiceManage, ZabbixDubboService zabbixDubboService) {
        this.cmdbServiceManage = cmdbServiceManage;
        this.zabbixDubboService = zabbixDubboService;
    }


    @Override
    public Object genMonitorData(MwMonitorHistoryParam param) {
        MwBaseMonitorDataResult baseData = new MwBaseMonitorDataResult();
        QueryItemHistoryParam itemHistoryParam = historyParamConvert(param);
        Map<String, ItemDropInfo> itemInfoByMap = new HashMap<>();
        MwMonitorProcessorConvert processorConvert = new MwMonitorProcessorConvert(cmdbServiceManage, zabbixDubboService);
        //获取查询监控参数context
        MonitorParamContext contextParam = processorConvert.getContextParam(itemHistoryParam, null);
        //获取查询监控processor
        MonitorProcessor processor = processorConvert.getMonitorProcessor(param);
        //具先监控参数context中的MwInstanceZabbixParam参数
        contextParam.setQueryMonitorParam(param);
        List<MwItemHistoryResult> historyResultList = new ArrayList<>();
        Map<String, ItemNameParam> collect = new HashMap<>();
        List<ItemNameParam> names = new ArrayList<>();
        Set<String> nameSet = new HashSet<>();
        List<String> sortNames = new ArrayList<>();
        ChartTypeEnum chartTypeEnum = getChartEnumByName(param.getChartType());
        if (processor != null) {

            contextParam.setParam(param);
            names = processor.getNames(contextParam);
            nameSet = names.stream().map(s -> s.getDevName()).collect(Collectors.toSet());
            if(CollectionUtils.isNotEmpty(param.getInterfaceDrops())){
                collect = names.stream().filter(s->param.getInterfaceDrops().contains(s.getDevName())).collect(Collectors.toMap(s -> s.getItemId(), s -> s, (o1, o2) -> o1));
            }else{
                collect = names.stream().collect(Collectors.toMap(s -> s.getItemId(), s -> s, (o1, o2) -> o1));
            }
            if(collect!=null && collect.size()>0){
                itemHistoryParam.setItemIds(new ArrayList<>(collect.keySet()));
            }
            contextParam.setParam(itemHistoryParam);

            switch (chartTypeEnum) {
                case rateLine://占用率组件，监控项设备名称合并处理
                    itemInfoByMap = itemHistoryParam.getItemInfoByItemName();
                    sortNames = new ArrayList<>();
                    break;
                default://其他组件，监控项设备名称拆分处理（DevName）
                    itemInfoByMap = itemHistoryParam.getItemInfoByItemId();
                    List<String> nameList = new ArrayList<>(nameSet);
                    sortNames = nameList.stream().sorted().collect(Collectors.toList());
            }
            setItemInfoToDevName(itemInfoByMap, collect);
            contextParam.setParam(itemHistoryParam);
            //如果为最近一小时，
            if (param.getDateType() == 1) {
                //取历史数据
                List<MWItemHistoryDTO> monitorHistoryData = processor.getMonitorHistoryData(contextParam);
                historyResultList = monitorConvertDataHandle(monitorHistoryData, param, itemInfoByMap);
            } else {
                //趋势数据，1 = {MWItemHistoryDTO@23752} "MWItemHistoryDTO(itemid=2132802, clock=1709535034, value=2, ns=741050507, value_max=null, value_avg=null, value_min=null)"
                List<MWItemHistoryDTO> monitorTrendData = processor.getMonitorTrendData(contextParam);
                historyResultList = monitorConvertDataHandle(monitorTrendData, param, itemInfoByMap);
            }
        }
        baseData.setInterfaceDrops(sortNames);
        baseData.setItemTotalInfoList(historyResultList);
        return baseData;
    }
}
